import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wu_you/data/repository/auth_repository.dart';
import 'package:wu_you/data/repository/trad_repository.dart';
import 'package:wu_you/data/repository/user_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/model/user/trad_model.dart';
import 'package:wu_you/model/user/user_model.dart';
import 'package:wu_you/page/user/page_withdraw_record.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/state/bloc/http_bloc.dart';
import 'package:wu_you/state/bloc/trad_bloc.dart';
import 'package:wu_you/state/bloc/user_bloc.dart';
import 'package:wu_you/utils/input_util.dart';
import 'package:wu_you/utils/navigator_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/utils/extension_utils.dart';
import 'package:wu_you/widgets/countdown_view.dart';
import 'package:wu_you/widgets/http_status_widget.dart';

///提现
class WithDrawPage extends StatefulWidget{
  @override
  WithDrawPageState createState() => WithDrawPageState();
}
class WithDrawPageState extends State<WithDrawPage>{
  TextEditingController _controller = TextEditingController();
  TextEditingController _controller1 = TextEditingController();
  final _countdownKey = GlobalKey<CountdownViewState>();
  String _number = "";


  var future;

  String comRatio = "0.0";
  @override
  void initState() {
    super.initState();
    future = TradRepository().getPublishInfo(1);
  }

  var message;
  String _select = "0";
  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text("${message['user2']}"),
      ),
      body: SingleChildScrollView(
        child: HttpWidget<WithdrawInfo, WithdrawInfoBloc>(
          create: (context) => WithdrawInfoBloc()..add(HttpEvent()),
          child: (context, data) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                    width: double.infinity,
                    margin: EdgeInsets.all(12),
                    padding: EdgeInsets.only(left: 12,right: 12,top: 18,bottom: 18),
                    decoration: BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage(Utils.getImgPath('ic_user_tx_bg'),), fit: BoxFit.fill
                      ),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text("${message['text44']}",style: TextStyle(color: Colors.white),),
                        SizedBox(height: 12,),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Image.asset(Utils.getImgPath("ic_user_tx_tips"),width: 45,height: 45,fit: BoxFit.fill,),
                            SizedBox(width: 12,),
                            Text("${data.money}",style: TextStyle(fontSize: 25,color: Colors.white,fontWeight: FontWeight.bold),)
                          ],
                        ),
                        SizedBox(height: 20,),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Container(
                              child: Text(""),
                            ),
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text("${message['text45']}",style: TextStyle(color: Colors.white),),
                                Icon(Icons.arrow_right_outlined,color: Colors.white,)
                              ],
                            ).addGesture(() {
                              NavigatorUtil.navigateToPage(context, WithdrawRecordPage(num: "${data.successMoney}",));
                            })
                          ],
                        )
                      ],
                    )
                ),
                Padding(padding: EdgeInsets.only(left: 15,top: 12,bottom: 2),
                  child: Text("${message['text46']}",style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),),
                ),
                TextFormField(
                  style: TextStyle(fontSize: 20,color: AppColors.textColor,fontWeight: FontWeight.bold),
                  maxLines: 1,
                  textAlignVertical: TextAlignVertical.center,
                  textInputAction: TextInputAction.next,
                  autofocus: false,
                  keyboardType: TextInputType.numberWithOptions(decimal: true),
                  inputFormatters: [
                    PrecisionLimitFormatter(2),
                    FilteringTextInputFormatter.allow(RegExp('[0-9.,]+'))
                  ],
                  controller: _controller,
                  onChanged: (value){
                    setState(() {
                      _number = value;
                    });
                    if(_number != ''){
                      double com = double.parse("${data.withdraw_fee}");
                      comRatio = "${(double.parse(_number) * com).toStringAsFixed(2)}";
                    }else{
                      double com = double.parse("${data.withdraw_fee}");
                      comRatio = "${(double.parse('0.0') * com).toStringAsFixed(2)}";
                    }
                  },
                  textAlign: TextAlign.start,
                  decoration: InputDecoration(
                    fillColor: Colors.white,
                    // prefixIcon: Align(
                    //   alignment: Alignment.centerLeft,
                    //   child: Padding(
                    //     padding: EdgeInsets.only(left: 12),
                    //     child: Text("", style: TextStyle(fontSize: 25)),
                    //   ),
                    // ),
                    prefixIconConstraints: BoxConstraints.loose(Size(40, 56)),
                    filled: true,
                    border: OutlineInputBorder(
                      borderSide: BorderSide.none,
                    ),
                    errorMaxLines: 1,
                    counterText: '',
                    contentPadding: EdgeInsets.all(15),
                    hintText: "${message['text47']}",
                    hintStyle: Theme.of(context).textTheme.bodyText1,
                  ),
                ),
                Divider(
                  height: 2,
                  color: HexColor("#EAEAEA"),
                ),
                TextFormField(
                  style: TextStyle(color: Colors.black,fontSize: 15),
                  maxLines: 1,
                  textAlignVertical: TextAlignVertical.center,
                  textInputAction: TextInputAction.done,
                  maxLength: 4,
                  keyboardType: TextInputType.numberWithOptions(),
                  autofocus: false,
                  obscureText: false,
                  cursorColor: Theme.of(context).primaryColor,
                  validator: (value) {
                    return value.length == 4 ? null : '${message['enterCode']}';
                  },
                  controller: _controller1,
                  decoration: InputDecoration(
                    fillColor: Colors.white,
                    filled: true,
                    prefixIconConstraints: BoxConstraints.loose(Size(64, 50)),
                    suffixIconConstraints: BoxConstraints.loose(Size(100, 56)),
                    suffixIcon: CountdownView(
                      key: _countdownKey,
                      hint: Text(
                        "${message['getCode']}",
                        style: TextStyle(color: AppColors.primaryColor, fontSize: 14),
                      ),
                      onPressed: () {
                        closeKeyboard(context);
                        _onGetCode();
                      },
                    ),
                    border: UnderlineInputBorder(
                      borderSide: BorderSide.none,
                      borderRadius: const BorderRadius.all(Radius.circular(24)),
                    ),
                    errorMaxLines: 1,
                    counterText: '',
                    contentPadding: EdgeInsets.only(left: 16, right: 16),
                    hintText: "${message['enterCode']}",
                    hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                  ),
                ),
                Divider(
                  height: 2,
                  color: HexColor("#EAEAEA"),
                ),
                Padding(padding: EdgeInsets.only(left: 15,top: 10),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      RichText(
                        text: TextSpan(children: [
                          TextSpan(
                              text: "${message['text48']}",
                              style: TextStyle(
                                  fontSize: 14, color: AppColors.textHintColor)),
                          TextSpan(
                              text: "$comRatio",
                              style: TextStyle(
                                  fontSize: 14, color: Colors.red)),
                          TextSpan(
                              text: "",
                              style: TextStyle(
                                  fontSize: 14, color: AppColors.textHintColor))
                        ]
                        ),
                        textAlign: TextAlign.center,
                      ),
                      SizedBox(width: 8,),
                      Image.asset(Utils.getImgPath("ic_box_rule"),width: 16,height: 16,).addGesture(() {
                        showCupertinoDialog(
                            context: context,
                            builder: (context) {
                              return CupertinoAlertDialog(
                                title: Text('${message['address12']}'),
                                content: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text('${message['text49']}${double.parse(data.withdraw_fee) * 100}%'),
                                    Text('${message['text55']}${data.withdraw_low}'),
                                    Text('${message['text56']}${data.withdraw_high}'),
                                  ],
                                ),
                                actions: <Widget>[
                                  CupertinoDialogAction(child: Text('${message['address15']}'),onPressed: (){
                                    Navigator.of(context).pop();
                                  },),
                                ],
                              );
                            });
                      }),
                    ],
                  ),
                ),
                Padding(padding: EdgeInsets.only(top: 25),
                  child: Divider(thickness: 8,color: HexColor("#F4F4F4"),),
                ),
                Padding(padding: EdgeInsets.only(left: 14,top: 15),
                  child: Text("${message['text50']}",style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),),
                ),

                FutureBuilder(
                    future: future,
                    builder: (context,data){
                      TradPubInfo tp = data.data;
                      if(tp != null && tp.payment != null && tp.payment.length != 0){
                        return Container(
                          height: 52.0 * tp.payment.length,
                          child: ListView.builder(
                            physics: NeverScrollableScrollPhysics(),
                            itemBuilder: (context,index){
                              String item = tp.payment[index];
                              return Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Row(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      _leadIcon(item),
                                      SizedBox(width: 12,),
                                      _titleText(item)
                                    ],
                                  ),
                                  SizedBox(
                                    child: Radio(
                                        value: item,
                                        groupValue: _select,
                                        onChanged: (value){
                                          setState(() {
                                            _select = value;
                                          });
                                        }
                                    ),
                                    width: 30,
                                    height: 30,
                                  ),
                                ],
                              ).addPadding(EdgeInsets.only(left: 16,right: 16,top: 16));
                            },
                            itemCount: tp.payment.length,
                          ),
                        );
                      }else{
                        return Container(
                          height: 110,
                          child: Center(
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Image.asset(Utils.getImgPath("ic_empty",), width: 60, fit: BoxFit.fitWidth,),
                                SizedBox(height: 10,),
                                Text("${message['text51']}",style: TextStyle(color: AppColors.textHintColor),),
                              ],
                            )
                          ),
                        );
                      }
                    }
                ),
                SizedBox(height: 40,),
                SizedBox(
                  width: double.infinity,
                  height: 42,
                  child: ElevatedButton(
                    child: Text("${message['text52']}"),
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(AppColors.primaryColor),
                      shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),
                    ),
                    onPressed: (){
                      _onSubmit(data);
                    },
                  ),
                ).addPadding(EdgeInsets.only(left: 25,right: 25,bottom: 25)),
              ],
            );
          }
        )
      ),
    );
  }

  void _onSubmit(WithdrawInfo model) async{
    String money = _controller.text;
    String smsCode = _controller1.text;
    if(money == ""){
      ToastUtils.show("${message['text47']}", context);
      return;
    }
    if(smsCode == ""){
      ToastUtils.show("${message['enterCode']}", context);
      return;
    }
    if(_select == "0"){
      ToastUtils.show("${message['text53']}", context);
      return;
    }
    if(double.parse(money) > double.parse("${model.money}")){
      ToastUtils.show("${message['text54']}", context);
      return;
    }
    if(double.parse(money) < double.parse("${model.withdraw_low}")){
      ToastUtils.show("${message['text55']}${model.withdraw_low}", context);
      return;
    }
    if(double.parse(money) > double.parse("${model.withdraw_high}")){
      ToastUtils.show("${message['text56']}${model.withdraw_high}", context);
      return;
    }
    closeKeyboard(context);
    LoadingApi.func(UserRepository().txApply(money,smsCode,_select), context,complete: (v){
      ToastUtils.show("$v", context);
      Future.delayed(const Duration(milliseconds: 800), () {
        Navigator.of(context).pop(1);
      });
    },error: (e){
      ToastUtils.show("$e", context);
    });
  }

  Widget _leadIcon(String type){
    Widget child;
    if(type == "1"){
      child = Image.asset(Utils.getImgPath('payment_one'),width: 30,height: 30,fit: BoxFit.fill,);
    }else if(type == "2"){
      child = Image.asset(Utils.getImgPath('payment_two'),width: 30,height: 30,fit: BoxFit.fill,);
    }else if(type == "3"){
      child = Image.asset(Utils.getImgPath('payment_three'),width: 30,height: 30,fit: BoxFit.fill,);
    }else if(type == "4"){
      child = Image.asset(Utils.getImgPath('payment_four'),width: 30,height: 30,fit: BoxFit.fill,);
    }else if(type == "5"){
      child = Image.asset(Utils.getImgPath('payment_five'),width: 30,height: 30,fit: BoxFit.fill,);
    }
    return child;
  }

  Widget _titleText(String type){
    Widget child;
    if(type == "1"){
      child = Text("${message['trad36']}",style: TextStyle(fontSize: 15,color: Colors.black),);
    }else if(type == "2"){
      child = Text("${message['trad37']}",style: TextStyle(fontSize: 15,color: Colors.black),);
    }else if(type == "3"){
      child = Text("${message['trad38']}",style: TextStyle(fontSize: 15,color: Colors.black),);
    }else if(type == "4"){
      child = Text("USDT",style: TextStyle(fontSize: 15,color: Colors.black),);
    }else if(type == "5"){
      child = Text("TNG",style: TextStyle(fontSize: 15,color: Colors.black),);
    }
    return child;
  }


  void _onGetCode(){
    _countdownKey.currentState.state = CountdownState.loading;
    LoadingApi.func(AuthRepository().getSmsCode(6), context,showLoading: false,complete: (value){
      _countdownKey.currentState.state = CountdownState.countdown;
      ToastUtils.show("$value", context);
    },error: (error){
      _countdownKey.currentState.state = CountdownState.init;
      ToastUtils.show("$error", context);
    });
  }
}




